package com.yc.admin.controller.common;

import com.google.code.kaptcha.Producer;
import com.yc.common.constant.CacheConstant;
import com.yc.common.constant.Constant;
import com.yc.common.core.domain.AjaxResult;
import com.yc.common.core.redis.RedisCache;
import com.yc.common.utils.CaptchaGeneratorUtil;
import com.yc.common.utils.sign.Base64;
import com.yc.common.utils.uuid.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@Api("验证码")
public class CaptchaController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @ApiOperation("生成登录验证码")
    public AjaxResult getCode() throws IOException {

        AjaxResult ajax = AjaxResult.success();

        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = CacheConstant.CAPTCHA_CODE_KEY + uuid;
        log.info(verifyKey);

        StringBuilder captcha = null;
        BufferedImage image = null;

        //生成验证码
        captcha = CaptchaGeneratorUtil.extracted();
        log.info("captcha is : {}", captcha);
        image = captchaProducer.createImage(String.valueOf(captcha));

        redisCache.setCacheObject(verifyKey, captcha, Constant.Captcha.CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
}
